package com.nxcy.mysql;

import java.sql.*;

public class DBUtils {
    private final static String CLASS_NAME = "com.mysql.cj.jdbc.Driver";
    private final static String DB_URL = "mysql.zhledu.cn";
    private final static int DB_PORT = 3306;
    private final static String DB_NAME = "school";
    private final static String DB_USERNAME = "school";
    private final static String DB_PASSWORD = "zhli2008";

    private Connection connection;

    /***
     * 获取连接
     * @return
     * @throws Exception
     */
    private Connection getConnection() throws Exception {
        Class.forName(CLASS_NAME);
        connection = DriverManager.getConnection("jdbc:mysql://" + DB_URL + ":" + DB_PORT + "/" + DB_NAME, DB_USERNAME, DB_PASSWORD);
        return connection;
    }

    /***
     * 执行查询
     * @param sql
     * @return
     * @throws Exception
     */
    public ResultSet executeQuery(String sql) throws Exception {
        Connection connection = getConnection();
        Statement stmt = connection.createStatement();
        return stmt.executeQuery(sql);
    }

    public PreparedStatement getPreparedStatement(String sql) throws Exception{
        Connection connection=getConnection();
        return  connection.prepareStatement(sql);
    }

    /***
     * 执行任何sql语句
     * @param sql
     * @return
     * @throws Exception
     */
    public boolean execute(String sql) throws Exception {
        Connection connection = getConnection();
        Statement stmt = connection.createStatement();
        return stmt.execute(sql);
    }

    public int executeUpdate(String sql) throws Exception {
        Connection connection = getConnection();
        Statement stmt = connection.createStatement();
        return stmt.executeUpdate(sql);
    }


    /***
     * 关闭连接
     */
    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
